package com.ptszyxx.popose.module.main.dynamic;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.constants.BundleConstant;
import com.ysg.http.data.AppViewModelFactory;
import com.ptszyxx.popose.common.weiget.DynamicImage;
import com.ptszyxx.popose.databinding.FragmentDynamicCommentBinding;
import com.ptszyxx.popose.module.main.dynamic.adapter.DynamicCommentAdapter;
import com.ysg.http.data.entity.dynamic.CommentEntity;
import com.ysg.http.data.entity.dynamic.DynamicResult;
import com.ptszyxx.popose.module.main.dynamic.vm.DynamicCommentVM;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.ysg.base.BaseFragment;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YImageUtil;
import com.ysg.utils.YKeyboardUtils;
import com.ysg.utils.YRecyclerViewUtil;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;
import com.ysg.widget.dialog.SheetDialog;
import com.ysg.widget.dialog.entity.DialogEntity;

import java.util.List;

public class DynamicCommentFragment extends BaseFragment<FragmentDynamicCommentBinding, DynamicCommentVM> {

    private DynamicCommentAdapter adapter;
    private View headerView;
    private TextView tvFollow;

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_dynamic_comment;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public DynamicCommentVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(DynamicCommentVM.class);
    }

    @Override
    public void initParam() {
        super.initParam();
        Bundle bundle = getArguments();
        if (bundle != null){
            viewModel.dynamicId = bundle.getString(BundleConstant.DYNAMIC_ID);
        }
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.requestDynamic();
        viewModel.requestCommentPage(true);
    }

    @Override
    public void initView() {
        super.initView();
    }

    @Override
    public void initAdapter() {
        super.initAdapter();
        adapter = new DynamicCommentAdapter(viewModel);
        YRecyclerViewUtil.init(getContext(), binding.recyclerView, adapter);
        headerView = LayoutInflater.from(getContext()).inflate(R.layout.item_dynamic, null);
        headerView.findViewById(R.id.viewHide).setVisibility(View.VISIBLE);
        adapter.addHeaderView(headerView);

        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.requestDynamic();
                viewModel.requestCommentPage(true);
            }
        });
        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.requestCommentPage(false);
            }
        });
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onRefreshEvent.observe(this, new Observer<List<CommentEntity>>() {
            @Override
            public void onChanged(List<CommentEntity> list) {
                setAdapterData(list);
            }
        });
        viewModel.uc.onHeaderEvent.observe(this, o->{
            setHeaderViewUI();
        });
        viewModel.uc.onRefreshItemEvent.observe(this, o -> {
            setRefreshItem();
        });
        viewModel.uc.onCommentEvent.observe(this, o -> {
            showCommentEdit();
        });
        viewModel.uc.onCommentCountEvent.observe(this, o -> {
            setCommentCountUI();
        });
        viewModel.uc.onCommentClearEvent.observe(this, o -> {
            binding.editCommit.setText("");
        });
        viewModel.uc.onMoreEvent.observe(this, o -> {
            showDialogMore();
        });
        viewModel.uc.onFollowEvent.observe(this, o -> setFollowUI());
    }

    /**
     * 显示头部
     */
    private void setHeaderViewUI() {
        if (viewModel.dynamicEntity == null){
            return;
        }
        //头像
        DynamicResult item = viewModel.dynamicEntity;
        ImageView ivAvatar = headerView.findViewById(R.id.ivAvatar);
        YImageUtil.show(ivAvatar, item.getPic());
        //昵称
        TextView tvNick = headerView.findViewById(R.id.tvName);
        tvNick.setText(item.getNick());
        //vip
        ImageView ivVip = headerView.findViewById(R.id.ivVip);
        if (YStringUtil.eq(1, item.getIsVip())) {
            ivVip.setVisibility(View.VISIBLE);
        } else {
            ivVip.setVisibility(View.GONE);
        }
        //男女
        ImageView sexImage = headerView.findViewById(R.id.ivSex);
        if (YStringUtil.eq(2, item.getSex())) {
            sexImage.setImageResource(R.mipmap.ic_girl);
        } else {
            sexImage.setImageResource(R.mipmap.ic_boy);
        }
        //实名认证
        ImageView ivShimingRZ = headerView.findViewById(R.id.ivZhenren);
        if (YStringUtil.eq(1, item.getStatus())) {
            ivShimingRZ.setVisibility(View.VISIBLE);
        } else {
            ivShimingRZ.setVisibility(View.GONE);
        }
        //发布时间
        TextView creationtime = headerView.findViewById(R.id.tvTime);
        creationtime.setText(item.getFabuTime() + "");
        //内容
        TextView messageItem = headerView.findViewById(R.id.tvContent);
        messageItem.setText(item.getMessage() + "");
        //点赞
        ImageView ivIsDianZan = headerView.findViewById(R.id.ivLike);
        if (YStringUtil.eq(1, item.getDzstate())) {
            ivIsDianZan.setImageResource(R.mipmap.ic_guanzhu_red);
        } else {
            ivIsDianZan.setImageResource(R.mipmap.ic_guanzhu_gray);
        }
        TextView tvDianZan = headerView.findViewById(R.id.tvLike);
        tvDianZan.setText(item.getGivenum() + "");
        //评论
        TextView tvPinglunNum = headerView.findViewById(R.id.tvCommentNum);
        tvPinglunNum.setText(item.getCommentnum() + "");
        //图片
        DynamicImage dynamicImage = headerView.findViewById(R.id.dynamicImage);
        dynamicImage.setData(item);

        //评论点击
        View viewComment = headerView.findViewById(R.id.viewComment);
        viewComment.setOnClickListener(v->{
            viewModel.commentType = 1;
            showCommentEdit();
        });
        tvFollow = headerView.findViewById(R.id.tvFollow);
        setFollowUI();
        tvFollow.setOnClickListener(v->{
            viewModel.requestFollow();
        });
    }

    private void setFollowUI(){
        tvFollow.setVisibility(View.VISIBLE);
        if (YStringUtil.eq(1, viewModel.dynamicEntity.getGuanzhuState())) {
            tvFollow.setText(getResources().getString(R.string.dynamic_follow_select));
            tvFollow.setTextColor(getResources().getColor(com.ysg.R.color.grayColor));
            tvFollow.setBackgroundResource(R.drawable.shape_shop_unselect);
        } else {
            tvFollow.setText(getResources().getString(R.string.dynamic_follow_unselect));
            tvFollow.setTextColor(getResources().getColor(com.ysg.R.color.white));
            tvFollow.setBackgroundResource(R.drawable.shape_follow_select);
        }
    }

    private void setCommentCountUI(){
        TextView tvPinglunNum = headerView.findViewById(R.id.tvCommentNum);
        try {
            tvPinglunNum.setText((Integer.valueOf(tvPinglunNum.getText().toString()) + 1) + "");
        }catch (Exception e){
        }
    }

    private void setAdapterData(List<CommentEntity> list){
        binding.refreshLayout.finishRefresh();
        binding.refreshLayout.finishLoadMore();
        if (YCollectionUtil.isNotEmpty(list)){
            if (1 == viewModel.pageNo){
                adapter.setList(list);
            }else{
                adapter.addData(list);
            }
        }else{
            binding.refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    private void setRefreshItem() {
        adapter.notifyItemChanged(viewModel.currentPosition);
    }

    /**
     * 回复评论
     */
    private void showCommentEdit(){
        binding.editCommit.setFocusable(true);
        binding.editCommit.setFocusable(true);
        binding.editCommit.setFocusableInTouchMode(true);
        binding.editCommit.requestFocus();
        YKeyboardUtils.show(binding.editCommit);
    }

    /**
     * 举报,删除
     */
    private void showDialogMore(){
        if (null == viewModel.dynamicEntity){
            return;
        }
        String[] item = new String[]{getResources().getString(R.string.report)};
        if (YStringUtil.eq(YSPUtils.getInstance().getUserId(), viewModel.dynamicEntity.getUserid())){
            item = new String[]{getResources().getString(R.string.report), getResources().getString(R.string.delete)};
        }

        YDialogUtil.getInstance().showSheet(getContext(), item).setOnSheetListener(new SheetDialog.OnSheetListener() {
            @Override
            public void onItemClick(DialogEntity entity) {
                if (YStringUtil.eq(getResources().getString(R.string.delete), entity.getName())){
                    viewModel.requestDynamicDelete();
                }else{
                    YToastUtil.showShort(getResources().getString(R.string.report));
                }
            }
        });
    }

}
